# !/usr/bin/env python
# -*-coding:utf-8 -*-
"""
# File       : default_config_plugin.py
# Time       ：2023/7/19 21:52
# Author     ：Y-aong
# version    ：python 3.7
# Description：
    获取全部的url路径
    Gets all url paths
"""
from flask import Flask

from apis.system_oauth.models import SystemPermission, SystemUser, SystemRole, SystemUserRoleRelation
from public.base_model import session_scope
from public.utils.const import DEFAULT_CONFIG


class DefaultConfig:
    def __init__(self, app=None):
        if app is not None:
            self.init_app(app)

        self.methods = ['GET', 'POST', 'PUT', 'DELETE']
        self.names = {
            'GET': 'get',
            'POST': 'create',
            'PUT': 'update',
            'DELETE': 'delete',
        }

    def init_app(self, app: Flask):
        self.get_url_path_method(app)
        self.create_default_config()
        self.create_user()

    def get_url_path_method(self, app: Flask):
        """
        获取所有的请求路径和请求方法,
        Gets all request paths and request methods
        """
        rules: dict = app.url_map.__dict__.get('_rules_by_endpoint')
        for key, rule in rules.items():
            url_path = str(rule[0].rule)
            _methods = list(rule[0].methods)
            methods = [item for item in _methods if item in self.methods]
            for method in methods:
                name = f'{url_path.replace("/", "")}_{self.names.get(method).lower()}'
                desc = f'{self.names.get(method).lower()}_{url_path.replace("/", "")}'
                permission = {
                    'name': name,
                    'method': method,
                    'path': url_path,
                    'desc': desc,
                    'active': 1
                }
                with session_scope() as session:
                    permission_obj = session.query(SystemPermission).filter(
                        SystemPermission.path == url_path, SystemPermission.method == method).first()
                    if not permission_obj:
                        obj = SystemPermission(**permission)
                        session.add(obj)
                        session.commit()

    @staticmethod
    def create_user(username='orderlines', password='orderlines', email='', phone='', admin=True):
        """
        创建默认的超级管理员用户。
        Create a default super administrator
        """
        from public.api_utils.jwt_utils import encrypt_password
        user_info = {
            'username': username,
            'password': encrypt_password(password),
            'email': email,
            'phone': phone
        }

        with session_scope() as session:
            obj = session.query(SystemUser).filter(
                SystemUser.username == username,
                SystemUser.active == 1).first()
            if not obj:
                obj = SystemUser(**user_info)
                session.add(obj)
                session.commit()
            user_id = obj.id

        if admin:
            with session_scope() as session:
                admin_role = session.query(SystemRole).filter(SystemRole.role_name == 'admin').first()
                if not admin_role:
                    obj = SystemRole(**{'role_name': 'admin', 'desc': 'super admin'})
                    session.add(obj)
                    admin_role_id = obj.id
                else:
                    admin_role_id = admin_role.id
                user_role_obj = SystemUserRoleRelation(**{'user_id': user_id, 'role_id': admin_role_id})
                session.add(user_role_obj)
                session.commit()

    @staticmethod
    def create_default_config():
        """
        创建orderlines默认配置
        create orderlines default config
        @return:
        """
        from apis.config.models import BaseConfig

        for item in DEFAULT_CONFIG:
            with session_scope() as session:
                obj = session.query(BaseConfig).filter(
                    BaseConfig.config_name == item.get('config_name'), BaseConfig.active == 1).first()
                if not obj:
                    conf = BaseConfig(**item)
                    session.add(conf)
                    session.commit()
